package com.woniu.component;

import com.woniu.entity.Order;
import com.woniu.entity.OrderItem;
import com.woniu.entity.Product;
import com.woniu.mapper.OrderItemMapper;
import com.woniu.mapper.OrderMapper;
import com.woniu.mapper.ProductMapper;
import com.woniu.util.OrderContext;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.List;

@LiteflowComponent("checkInventory")
public class CheckInventoryNode extends NodeComponent {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public void process() throws Exception {
        // ✅ 获取上下文
        OrderContext context = this.getContextBean(OrderContext.class);
        if (context == null) {
            System.out.println("❌ context 为 null！上下文未传递成功！");
            throw new RuntimeException("订单上下文为空");
        }
        System.out.println("✅ context 已获取: " + context);
        String orderId = context.getOrderId();

        // 查询订单
        Order order = orderMapper.getById(orderId);
        if (order == null) {
            context.setErrorMsg("订单不存在");
            context.setInventoryOk(false);
            System.out.println("❌ 库存检查失败：订单不存在");
            return;
        }

        // 查询订单项
        List<OrderItem> orderItems = orderItemMapper.findOrderDetail(orderId);
        if (orderItems == null || orderItems.isEmpty()) {
            context.setErrorMsg("订单项为空");
            context.setInventoryOk(false);
            System.out.println("❌ 库存检查失败：订单项为空");
            return;
        }

        // 校验并扣减库存
        for (OrderItem item : orderItems) {
            Integer productId = item.getProductId();
            Integer buyNum = item.getBuyNum();

            // 查询商品
            Product product = productMapper.findByProductId(productId);
            if (product == null) {
                context.setErrorMsg("商品不存在，ID: " + productId);
                context.setInventoryOk(false);
                System.out.println("❌ 库存检查失败：商品不存在");
                return;
            }

            BigDecimal needStock = BigDecimal.valueOf(buyNum);
            if (needStock.compareTo(product.getStock()) > 0) {
                context.setErrorMsg("商品【" + product.getName() + "】库存不足，需" + needStock + "，剩余" + product.getStock());
                context.setInventoryOk(false);
                System.out.println("❌ 库存检查失败：" + context.getErrorMsg());
                return;
            }

            // ✅ 执行扣减库存（数据库原子操作）
            int result = productMapper.reduceStock(Long.valueOf(productId), buyNum);
            if (result <= 0) {
                context.setErrorMsg("商品【" + product.getName() + "】库存扣减失败，可能已被其他请求占用");
                context.setInventoryOk(false);
                System.out.println("❌ 扣减库存失败：商品ID=" + productId);
                return;
            }

            System.out.println("✅ 成功扣减商品【" + product.getName() + "】库存：" + buyNum);
        }

        // 全部校验通过且库存已扣减
        context.setInventoryOk(true);
        System.out.println("✅ 库存检查通过，且库存已成功扣减");
    }
}